<template>
  <el-dialog
      title="修改用户信息"
      v-model="dialogVisible"
      width="400px"
      @close="closePopup"
  >
    <el-form :model="userData"  ref="reinfoForm">

      <!-- 其他字段可以继续添加 -->
      <el-form-item
          v-for="(value, key) in user_userInfo"
          :key="key"
          :label="value.verbose_name"
          :prop="key">
        <component
            :is="inputComponentForType(value, key).component"
            v-bind="inputComponentForType(value, key).props"
            v-model="userData[key]"
        >
          <template v-if="inputComponentForType(value, key).component === ElSelect">
            <el-option
                v-for="option in value.choices"
                :key="option"
                :label="option"
                :value="option"
            ></el-option>
          </template>
        </component>
      </el-form-item>
      <span slot="footer" class="dialog-footer">
      <el-button @click="closePopup">取消</el-button>
      <el-button type="primary"
               :loading="submitFormLoading"
               :disabled="submitFormLoading"
               @click="submitForm">{{ submitFormLoading ? '正在修改' : '确认' }}
      </el-button>
    </span>
    </el-form>
  </el-dialog>
</template>

<script setup>
import {ref, reactive, onMounted, watchEffect} from 'vue'
import setting from "@/setting.js";
import {ElDatePicker, ElInput, ElMessage, ElSelect, ElSwitch, ElText} from "element-plus";
import {jsonApi} from "@/global.js";
const userData = reactive({});
const user_userInfo = ref({});
const getUserInfoisOK= ref(false);
const  submitFormLoading= ref(false);
const inputComponentForType = (value, key) => {
  const componentMap = {
    'CharField': ElInput,
    'IntegerField': ElInput,
    'DateTimeField': ElDatePicker,
    'BooleanField': ElSwitch,
  };

  if (key === 'base_score') {
    return { component: ElInput, props: { readonly: true } };
  }
  if(value.type === 'JSONField'){
    return { component: ElText, props: { readonly: true } };
  }
  if (value.choices !== null) {
    return {
      component: ElSelect,
      props: {
        options: value.choices.map(choice => ({
          label: choice,
          value: choice,
        }))
      }
    };
  }

  return {
    component: componentMap[value.type] ? componentMap[value.type] : ElInput,
    props: {}
  };


};
const getUserInfo=async ()=>{
/*
* /user/info/ post
* fetch
* */
  try {

    const response = await jsonApi('/user/info/');

    const data = await response.json();
    if (response.ok) {
      localStorage.setItem('userinfo', JSON.stringify(data));
      await getReportInfo()
    } else {
      ElMessage({
        message: '获取用户信息失败:' + data.detail,
        type: 'error'
      })
    }
  } catch (e) {
    ElMessage({
      message: '获取用户信息失败:' + e,
      type: 'error'
    })
  }


}
const submitForm = async () => {
  /*
  * /user/register/*/

  try {
    submitFormLoading.value = true;
    const response = await jsonApi('/user/reinfo/',JSON.stringify(userData));
    const data = await response.json();
    if (response.ok) {
      ElMessage({message: '修改成功,正在更新信息', type: 'success', duration: 2000});
      submitFormLoading.value = false;
      closePopup();

    } else {
      ElMessage({
        type: 'error',
        message: '修改失败:' + data.error,
        duration: 2000
      });
      submitFormLoading.value = false;
    }
  } catch (e) {
    ElMessage({
      type: 'error',
      message: '修改失败:' + e,
      duration: 2000
    });
    submitFormLoading.value = false;

  }
};
const dialogVisible= ref(false)
const open = () => {
  getUserInfo();
  dialogVisible.value = true;
};
function closePopup() {
  dialogVisible.value = false;
}
defineExpose({
  open,
});


//初始化函数
const getReportInfo = async () => {
  //获取时需要排除的字段

    const response = await jsonApi('/user/getfields/',JSON.stringify({}),false);
    const data = await response.json();
    if (response.ok) {
      //将字符串转为对象
       localStorage.setItem('registeinfo', JSON.stringify(data));
       user_userInfo.value = JSON.parse(localStorage.getItem('registeinfo'))['User'];
       const get_excludeFields = ['id', 'model_name', 'attachment', 'username', 'password',"is_superuser","avatar"];
       // 使用 forEach 循环来遍历对象的所有键
       get_excludeFields.forEach(field => {
         // 如果报告信息中存在要排除的字段，则删除它
         if (user_userInfo.value.hasOwnProperty(field)) {
           delete user_userInfo.value[field];
         }
       });
       for(let key in user_userInfo.value){
         userData[key] = JSON.parse(localStorage.getItem('userinfo'))[key];
       }
    } else {
      ElMessage({
        type: 'error',
        message: '获取失败:' + data.error,
        duration: 2000
      })
    }
};
// watchEffect(async () => {
//   await getUserInfo();
//   if(getUserInfoisOK.value){
//      await getReportInfo();
//   }
// });

</script>